package com.cqs.leetcode.array;


import java.util.ArrayList;
import java.util.List;

/**
 * lixw
 * 2021/10/8
 **/
public class SpiralMatrix54 {

    //
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if (matrix.length == 0) return list;
        int M = matrix.length, N = matrix[0].length;
        int top = 0, right = N - 1, bottom = M - 1, left = -1;
        while (top <= bottom && right >= left) {
            for (int i = ++left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
            for (int i = ++top; i <= bottom && left <= right; i++) {
                list.add(matrix[i][right]);
            }
            for (int i = --right; i >= left && top <= bottom; --i) {
                list.add(matrix[bottom][i]);
            }
            for (int i = --bottom; i >= top && left <= right; --i) {
                list.add(matrix[i][left]);
            }
        }
        return list;
    }

    public List<Integer> spiralOrder2(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if (matrix.length == 0) return list;
        int M = matrix.length, N = matrix[0].length;
        int loop = 0, cnt = M * N;
        while (cnt > 0) {
            int idx = loop;
            while (idx < N - loop && --cnt >= 0) {
                list.add(matrix[loop][idx++]);
            }
            idx = loop + 1;
            while (idx < M - loop && --cnt >= 0) {
                list.add(matrix[idx++][N - 1 - loop]);
            }
            idx = N - 1 - loop - 1;
            while (idx >= loop && --cnt >= 0) {
                list.add(matrix[M - 1 - loop][idx--]);
            }
            idx = M - 1 - loop - 1;
            while (idx >= loop + 1 && --cnt >= 0) {
                list.add(matrix[idx--][loop]);
            }
            loop++;
        }
        return list;
    }

    public static void main(String[] args) {
        SpiralMatrix54 s = new SpiralMatrix54();
//        int[][] cs = {{1,2,3},{4,5,6},{7,8,9}};
        int M = 5;
        int N = 6;
        int[][] cs = new int[M][N];
        int cnt = 0;
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                cs[i][j] = ++cnt;
            }
        }
        List<Integer> list = s.spiralOrder(cs);
        List<Integer> list2 = s.spiralOrder2(cs);
        System.out.println(list);
        System.out.println(list2);

    }
}
